
import org.junit.Test;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Random;

public class SortTest {



	@Test
	public void simpleSort() {

		Random random = new Random();
		List<Integer> list = new ArrayList<>();
		list.add(random.nextInt(100));
		list.add(random.nextInt(100));
		list.add(random.nextInt(100));

		println(list);

		//参数形式的lambda
		list.sort(Comparator.comparing(i -> i));
		println(list);

		//方法引用 + 复合方法
		list.sort(Comparator.comparingInt(Integer::intValue).reversed());
		println(list);

		//利用stream排序
		System.out.println("---");
		list.stream().sorted().forEach(System.out::println);
	}

	@Test
	public void nullSort() {
		Random random = new Random();
		List<Integer> list = new ArrayList<>();
		list.add(random.nextInt(100));
		list.add(random.nextInt(100));
		list.add(random.nextInt(100));
		list.add(null);

		//这个会报错
//		list.sort(Comparator.comparing(Integer::intValue));

		//把null放在最前面
		list.sort(Comparator.nullsFirst(Comparator.comparing(Integer::intValue)));
		println(list);

		//把null放在最后面
		list.sort(Comparator.nullsLast(Comparator.comparing(Integer::intValue)));
		println(list);
	}

	public void println(List list) {
		System.out.println("---");
		list.forEach(System.out::println);
	}


}
